/*
 * Copyright (c) 2021 Talkweb Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "light_demo.h"

#define ENV_LIGHT_LEVEL_LOW     1000 //低环境光AD值，模拟黄昏
#define ENV_LIGHT_LEVEL_LOWEST  1500 //超低环境光AD值，模拟黑夜

int LightSensorVal(unsigned short* val)
{
    int ret = IoTAdcRead(IOT_ADC_CHANNEL_6,val, IOT_ADC_EQU_MODEL_8, IOT_ADC_CUR_BAIS_DEFAULT, 256);
    if(ret != IOT_SUCCESS)
    {
        printf("Failed to read adc! Err code = %d\n", ret);
    }  
    return ret;    
}

int GetLightAverageVal(unsigned char cnt)
{
    unsigned short readVal = 0;
    unsigned int totalVal = 0, totalCnt = 0;

    for(unsigned char i=0; i<cnt; i++)
    {
        if(LightSensorVal(&readVal) == IOT_SUCCESS)
        {
            totalVal += readVal;
            totalCnt++;
        }
        usleep(50000);
    }

    return (totalVal/totalCnt); 
}

enum ENV_LIGHT_STATE GetEnvLightState(void)
{
    enum ENV_LIGHT_STATE lightState = LIGHT_DAY;

    //获取当前环境光照平均值
    int lightVal = GetLightAverageVal(5);

    //当前为黑夜环境
    if(lightVal > ENV_LIGHT_LEVEL_LOWEST)
    {
        lightState = LIGHT_NIGHT;
    }

    //当前为黄昏环境
    else if(lightVal > ENV_LIGHT_LEVEL_LOW)
    {
        lightState = LIGHT_DUSK;
    } 

    //当前为白天环境
    else
    {
        lightState = LIGHT_DAY;
    } 

    return  lightState;
}
